import router from './router'
// import store from './store'
import { MessageBox } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getCurrentRole, getToken, getLoginBussinessPlatform,setCurrentRole, setRoles } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
// import { generatedMenu, getMenuByRoleId } from '@/api/dealRouter'
import { generatedMenu, getMenuRoles } from '@/api/dealRouter'
import { allRouters, defaultConstRoutesLength } from '@/router/index'
import store from '@/store/index'
import { MenuTypeEnum, AccessUrl} from '@/consts'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = [] // no redirect whitelist
// const newRoute = generatedMenu(allRouters, JSON.parse(sessionStorage.getItem('routeData')))
// 路由过滤，钩子函数

// const isHanleRoutes = false

router.beforeEach(async(to, from, next) => {
  // start progress bar




  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)
  // determine whether the user has logged in
  if (whiteList.includes(to.path)) {
    // in the free login whitelist, go directly
    next()
  } else {
    const hasToken = getToken()
    if (hasToken) {
      if (getLoginBussinessPlatform() !== MenuTypeEnum.MANEGE) {
        // return window.history.back()
        switch (getLoginBussinessPlatform()) {
          case MenuTypeEnum.FRONT:
            window.location.replace(AccessUrl.frontUrl)
            break
          case MenuTypeEnum.MANAGE:
            window.location.replace(AccessUrl.manageUrl)
            break
        }
        return
      }

      if (router.options.routes.length === defaultConstRoutesLength) {
        const currentRole = getCurrentRole()

        let Res = null
        try {
          // Res = await getMenuByRoleId(MenuTypeEnum.MANEGE, (currentRole || { id: '' }).id)
          const res = await getMenuRoles(currentRole)
          setCurrentRole(res.currentMenuRoleId)
          setRoles(res.availableRole)
          Res = res.menuVOS || []
        } catch (error) {
          handleRoutesError()
        }

        const Route = generatedMenu(allRouters, Res)
        if (!Route.length) return handleRoutesError()


        let isInitPath = true

        Route.find(item => {
          if (item.children && Array.isArray(item.children) && item.children.length) {
            const find = item.children.find(childItem => childItem.path === to.path)
            if (find) {
              isInitPath = false
              return
            }
          }
          if (item.path === to.path) {
            isInitPath = false
            return
          }
        })

        // eslint-disable-next-line
        Route.forEach(item => {
          router.options.routes.push(item)
        })
        router.addRoutes(Route.concat([{ path: '*', redirect: '/404', hidden: true }]))

        if (to.path === '/' || to.path === '/login' || isInitPath) {
          if (Route[0].children && Route[0].children.length) {
            const path = Route.find(item => !item.hidden).children.find(item => !item.hidden).path
            next({ path, replace: true })
          } else {
            next({ path: Route[0].path, replace: true })
          }
        } else {
          next({ ...to, replace: true })
        }
      } else {
        if (to.path === '/login' || to.path === '/') {
          if (router.options[defaultConstRoutesLength].children && router.options[defaultConstRoutesLength].children.length) {
            next({ path: router.options[defaultConstRoutesLength].children.find(item => !item.hidden).path })
          } else {
            next({ path: router.options[defaultConstRoutesLength].path })
          }
        } else {
          next()
        }
      }
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      // next(`/login`)
      handleRoutesError('当前是未登陆状态，请点击确定返回登陆页')
    }
  }




  NProgress.done()
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})


function handleRoutesError(title = '当前没有权限进入，请点击确定返回登陆页') {
  MessageBox.confirm(title, {
    confirmButtonText: '确定',
    showClose: false,
    showCancelButton: false,
    closeOnClickModal: false,
    closeOnPressEscape: false,
    type: 'warning',
  }).then(() => {
    // window.location.href = AccessUrl.indexUrl
    store.dispatch('user/logout').then(() => {
      window.location.replace(AccessUrl.indexUrl)
    })
  })
}
